/**
 * Created by Administrator on 2017/10/24
 */
import React from 'react';
import { WeaTop, WeaTab, WeaRightMenu, WeaCheckbox, WeaBrowser, WeaLocaleProvider,WeaTools } from 'ecCom';
import { Button, Modal, message } from 'antd';
import { WeaTableNew } from 'comsMobx';
import AddAgent from './AddAgent';
import { inject, observer } from 'mobx-react';
import BatchEdit from './BatchEdit';
import EditAndSaveOther from './EditAndSaveOther';
import TemplateManage from './TemplateManage';
import allStore from '../../stores';
import { Condition, getAdButtons } from '../list/ListCondition';
import WfInterface from '../../interface';
import * as WORKFLOW_AGENT from '../../apis/agent';
import { Synergy } from 'weaPortal';
import '../../style/agent.less';

const WeaTable = WeaTableNew.WeaTable;
const getLabel = WeaLocaleProvider.getLabel;
const Base64 = WeaTools.Base64;

@inject('wfAgentStore')

@observer

export default class Main extends React.Component {
    constructor(props) {
        super(props);
    }

    doInit() {
        const {location} = this.props;
        const { wfAgentStore } = this.props;
        const { initDatas, doSearch } = wfAgentStore;
        initDatas(location.query);
        doSearch();
        _ListenerCtrl.bind();
    }

    varTemp = {
      btns: [],
      rightBtnsB: [],
      rightBtnsR: []
    }
    componentDidMount() {
        const { wfAgentStore,location } = this.props;
        const { jumpTab } = location.query;
        if(jumpTab) {//通过URL参数跳转到指定的Tab
            this.switchTab(jumpTab);
        } else {
            this.doInit();
        }
    }

    shouldComponentUpdate(nextProps, nextState) {
        return true;
    }

    componentWillUnmount() {
        const { wfAgentStore } = this.props;
        wfAgentStore.clearStatus();
        _ListenerCtrl.unbind();
    }

    componentWillReceiveProps(nextProps) {
        if (this.props.location.key !== nextProps.location.key) {
            const { wfAgentStore } = this.props;
            wfAgentStore.clearStatus();
            this.doInit();
        }
    }

    switchTab = (tabKey) => {
        const { wfAgentStore } = this.props;
        const { setParams, setViewcondition } = wfAgentStore;
        tabKey = parseInt(tabKey);
        switch (tabKey) {
            case 0:
                setParams(0, 0);
                break;
            case 1:
                setParams(1, 1);
                break;
            case 2:
                setParams(1, 0);
                break;
            default:
                setParams(0, 1);
        }
        setViewcondition(tabKey);
        this.doInit();
    }

    addAgent = () => {
        const callback = () =>{
            const { wfAgentStore } = this.props;
            wfAgentStore.addAgent(true, { symbol: 'addAgent' });
        }
        WfInterface.execBtnEvent("agent", "addAgent", callback);
    }

    batchEdit = () =>  {
        const { wfAgentStore } = this.props;
        const ids = this.getSelectedRowKeysTail();
        wfAgentStore.batchEdit(true, ids);
    }

    batchBack = () => {
        const ids = this.getSelectedRowKeysTail();
        window.agentOperate.takeBackBatch(ids, false);
    }

    getSelectedRowKeysTail = () => {
        const { wfAgentStore } = this.props;
        const { tableStore } = wfAgentStore;
        const tableNow = tableStore;
        const selectedRowKeys = tableNow.selectedRowKeys;
        const idsJson = JSON.stringify(selectedRowKeys);
        let ids = idsJson.slice(1, idsJson.length - 1).replace(/\"/g, "");
        return ids;
    }

    importTemplateAndNewAgent = (id, name) => {
        const { wfAgentStore } = this.props;
        wfAgentStore.addAgent(true, { symbol: 'importTemplate', templateid: id })
    }

    newTemplate = () =>  {
        const { wfAgentStore } = this.props;
        wfAgentStore.addAgent(true, { symbol: 'addTemplate' })
    }

    deleteTemplate = (ids) => {
        window.agentOperate.deleteTemplate(ids);
    }

    getImportWeaBrowser(type = 'R', ) {

        const refName = 'import' + type;
        return (
            <WeaBrowser ecId={`${this && this.props && this.props.ecId || ''}_WeaBrowser@5jfqc4`}
                ref={refName}
                type={'agentTemplate'}
                customized={true}
                hasAdvanceSerach="true"
                title={getLabel(32385, '从模板导入')}
                icon="icon-coms-workflow"
                iconBgcolor="#0079DE"
                zIndex={990}
                pageSize={10}
                buttons={[
                    (<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@8uyp7j@close`} type='glost' onClick={() => this.refs[refName].closeModal()}>{getLabel(31129, '取消')}</Button>),
                ]}
                checkHook={(id, name) => this.importTemplateAndNewAgent(id, name)}
            >
                {
                    type === 'T' &&
                    <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@67zq7a`} type='primary'>{getLabel(32385, '从模板导入')}</Button>
                }
                {
                    (type === 'R' || type === 'B') &&
                    <span>{getLabel(32385, '从模板导入')}</span>
                }
            </WeaBrowser>
        )

    }

    getRightMenu(type = 'R') {
        const { wfAgentStore } = this.props;
        const { viewcondition, tableStore } = wfAgentStore;
        const ids = this.getSelectedRowKeysTail();
        let btns = [];
        switch (parseInt(viewcondition)) {
            case 0:
                btns.push(
                    {
                        key: "addAgent",
                        icon: <i className="icon-coms-Add-to-o" />,
                        content: getLabel(33242, '新建代理'),
                        onClick: key => {
                            this.addAgent();
                        }
                    },
                    {
                        key: "templateImport",
                        icon: <i className="icon-coms-Batch-delete" />,
                        content: this.getImportWeaBrowser(type),

                    },
                    {
                        key: "templateManagement",
                        icon: <i className="icon-coms-Approval-o" />,
                        content: getLabel(20823, '模板管理'),
                        onClick: key => {
                            allStore.wfTemplateManageStore.templateManage(true);
                        }
                    },

                    {
                        key: "log",
                        icon: <i className="icon-coms-Print-log" />,
                        content: getLabel(383518, '批量编辑'),
                        disabled: !ids,
                        onClick: key => {
                            this.batchEdit();
                        }
                    }, {
                        key: "showCustomization",
                        icon: <i className="icon-coms-Batch-delete" />,
                        content: getLabel(33243, '批量收回'),
                        disabled: !ids,
                        onClick: key => {
                            this.batchBack();
                        }
                    }, {
                        key: "colSet",
                        icon: <i className='icon-workflow-Right-menu-Custom' />,
                        content: getLabel(32535, '显示列定制'),
                        onClick: key => {
                            tableStore.setColSetVisible(true);
                            tableStore.tableColSet(true);
                        }
                    }
                );
                break;
            case 1:
            case 2:
                btns.push({
                    key: "colSet",
                    icon: <i className='icon-workflow-Right-menu-Custom' />,
                    content: getLabel(32535, '显示列定制'),
                    onClick: key => {
                        tableStore.setColSetVisible(true);
                        tableStore.tableColSet(true);
                    }
                },

                )
                break;
            default:
                btns.push(
                    {
                        key: "addAgent",
                        icon: <i className="icon-coms-Add-to-o" />,
                        content: getLabel(33242, '新建代理'),
                        onClick: key => {
                            this.addAgent();
                        }
                    },
                    {
                        key: "templateImport",
                        icon: <i className="icon-coms-Batch-delete"></i>,
                        content: this.getImportWeaBrowser(type),
                    },
                    {
                        key: "templateManagement",
                        icon: <i className="icon-coms-Approval-o"></i>,
                        content: getLabel(20823, '模板管理'),
                        onClick: key => {
                            allStore.wfTemplateManageStore.templateManage(true);
                        }

                    },
                    {
                        key: "colSet",
                        icon: <i className='icon-workflow-Right-menu-Custom' />,
                        content: getLabel(32535, '显示列定制'),
                        onClick: key => {
                            tableStore.setColSetVisible(true);
                            tableStore.tableColSet(true);
                        }
                    }
                )
        }

        return btns;
    }

    getButtons() {
        let btns = [];
        const ids = this.getSelectedRowKeysTail();
        const { wfAgentStore } = this.props;
        const { viewcondition
        } = wfAgentStore;
        if (viewcondition == "0" || viewcondition == "3") {
            btns = [
                (<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@nuxqof@addAgent`} type='primary' onClick={() => this.addAgent()}>{getLabel(33242, '新建代理')}</Button>),
                (
                    this.getImportWeaBrowser('T')
                ),
                (<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@fh8xqe@templateManage`} type='primary' onClick={() => allStore.wfTemplateManageStore.templateManage(true)}>{getLabel(20823, '模板管理')}</Button>),
                (<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@w3t8eo@batchEdit`} type='primary' disabled={!ids} onClick={() => this.batchEdit()}>{getLabel(383518, '批量编辑')}</Button>),
                (<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@yvuwto@batchBack`} type='primary' disabled={!ids} onClick={() => this.batchBack()}>{getLabel(33243, '批量收回')}</Button>),
            ];
        }
        return btns;
    }

    getAgentTabs = () => {
        const wfAgent = [
            {
                key: 'myAgent',
                title: getLabel(383596, '我的代理设置'),
                tabKey: 0
            }, {
                key: 'iToDoAgent',
                title: getLabel(383597, '我代处理的流程'),
                tabKey: 1
            }, {
                key: 'otherToDoAgent',
                title: getLabel(383598, '交办他人的流程'),
                tabKey: 2
            }, {
                key: 'allAgent',
                title: getLabel(383599, '全部代理设置'),
                tabKey: 3
            }
        ];
        return wfAgent;
    }
    hideSearchAd = () => this.props.wfAgentStore.setShowSearchAd(false);

    setShowSearchAd = bool => { this.props.wfAgentStore.setShowSearchAd(bool)};
    onSearchChange = v => { wfAgentStore.appendFormFields({ requestname: { value: v } }) };
    onSearch = v => { wfAgentStore.doSearch() };
    closeImportModal = () => {
      this.refs.importT.closeModal();
      this.refs.importB.closeModal();
      this.refs.importR.closeModal();
    }
    closeManageModal = () => {
      allStore.wfTemplateManageStore.templateManage(false)
    }
    reloadManagerModal = () => {
      allStore.wfTemplateManageStore.reload();
    }
    render() {
        const { wfAgentStore } = this.props;
        const { viewcondition, title, tableStore, loading, showSearchAd, form, agented } = wfAgentStore;
        const formParams = form.getFormParams() || {};

        const wfAgent = this.getAgentTabs();
        this.varTemp.btns = this.varTemp.rightBtnsR = this.varTemp.rightBtnsB = [];
        this.varTemp.btns = this.getButtons();
        this.varTemp.rightBtnsB = this.getRightMenu('B');
        this.varTemp.rightBtnsR = this.getRightMenu('R')
        return (
            <div className="wf-agent-list">
                <WeaRightMenu ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@o7d10h`}
                    datas={this.varTemp.rightBtnsR}
                    collectParams={{
                        favname: title,
                        favouritetype: 2,
                        objid: 0,
                        importantlevel: 1,
                    }}
                >
                    <WeaTop ecId={`${this && this.props && this.props.ecId || ''}_WeaTop@as73oh`}
                        title={title}
                        loading={loading}
                        icon={<i className="icon-coms-workflow" />}
                        iconBgcolor="#0079DE"
                        buttons={this.varTemp.btns} // 右侧操作按钮
                        buttonSpace={10}
                        showDropIcon={true}
                        dropMenuDatas={this.varTemp.rightBtnsB}    // 下拉菜单数据
                    >

                        <TemplateManage ecId={`${this && this.props && this.props.ecId || ''}_TemplateManage@qllhjc`}
                            newTemplate={ this.newTemplate}
                            deleteTemplate={this.deleteTemplate}
                        />

                        <EditAndSaveOther ecId={`${this && this.props && this.props.ecId || ''}_EditAndSaveOther@y6k38s`} />

                        <AddAgent ecId={`${this && this.props && this.props.ecId || ''}_AddAgent@eazo47`}
                            closeImportModal={this.closeImportModal}
                            closeManagerModal={this.closeManageModal}
                            reloadManagerModal={this.reloadManagerModal}
                        />

                        <BatchEdit ecId={`${this && this.props && this.props.ecId || ''}_BatchEdit@3qt0bu`} />

                        <WeaTab ecId={`${this && this.props && this.props.ecId || ''}_WeaTab@0ya1zr`}
                            datas={wfAgent}
                            buttonsAd={getAdButtons(wfAgentStore)}
                            searchType={agented === 0 ? ['advanced'] : ['base', 'advanced']}
                            searchsBaseValue={formParams.requestname}
                            keyParam="tabKey"  //主键
                            hideSearchAd={this.hideSearchAd}
                            showSearchAd={showSearchAd}
                            selectedKey={viewcondition}
                            onChange={this.switchTab}
                            setShowSearchAd={this.setShowSearchAd}
                            searchsAd={
                                <Condition ecId={`${this && this.props && this.props.ecId || ''}_Condition@v471fl`} listStore={wfAgentStore} />
                            }
                            onSearchChange={this.onSearchChange}
                            onSearch={this.onSearch}
                        />
                        <WeaTable ecId={`${this && this.props && this.props.ecId || ''}_WeaTable@4rjipg`}
                            comsWeaTableStore={tableStore}
                            hasOrder={true}
                            needScroll={true}
                        />
                    </WeaTop>
                </WeaRightMenu>
                <Synergy ecId={`${this && this.props && this.props.ecId || ''}_Synergy@pwgvbt`} pathname='/workflow/agent' requestid="-1" />
            </div>
        )
    }
}

// 流程代理的全局操作
const operrate = function (store, refs) {

    return {
        store1: allStore.wfAgentStore,
        store2: allStore.wfDealRepetitionStore,
        edit(id) {
            let params = {
                agentid: id
            };
            this.store1.editAgent(true, { ...params, symbol: 'edit' });
        },
        saveAs(id) {
            let params = {
                agentid: id
            };
            this.store1.editAgent(true, { ...params, symbol: 'saveas' });
        },
        editTemplate(templateid) {
            this.store1.addAgent(true, { symbol: 'editTemplate', templateid });
        },
        editTemplateByid(templateid) {
            this.store1.addAgent(true, { symbol: 'editTemplate', templateid });
        },
        deleteTemplate(ids) {
            Modal.confirm({
                title: getLabel(131329, '信息确认'),
                content: getLabel(129890, '确定要删除吗？'),
                okText: getLabel(83446, '确定'),
                cancelText: getLabel(31129, '取消'),
                onOk: () => {
                    message.loading(getLabel(84024, '正在删除数据，请稍候...'), 0);
                    WORKFLOW_AGENT.deleteAgentTemplate({ ids }).then((datas) => {
                        if (datas.api_status) {
                            allStore.wfTemplateManageStore.reload();
                            message.destroy();
                            message.success(getLabel(20461, '删除成功'));
                        } else {
                            message.destroy();
                            message.error(getLabel(83473, '删除失败'));
                        }
                    }, () => {
                        message.destroy();
                        message.error(getLabel(83473, '删除失败'));
                    })
                }
            });

        },
        takeBackCur(id, belongOverlap) {    //收回此条代理
            const params = { symbol: "it", agentid: id };
            const curStore = belongOverlap === "true" ? this.store2 : this.store1;
            this.takeBack(params, curStore);
        },
        takeBackAll(id, otherpara) {     //收回全部代理
            const params = { agentid: id, symbol: "pt", bagentuid: otherpara };
            this.takeBack(params, this.store1);
        },
        takeBackBatch(ids, flag) {    //批量收回代理
            const params = { symbol: "mt", agentid: ids };
            this.takeBack(params, flag === true ? this.store2 : this.store1);
        },
        takeBack(params, curStore) {
            WORKFLOW_AGENT.takeBackPromptMsg(params).then((data) => {
                const agentStore = this.store1;
                Modal.confirm({
                    title: getLabel(131329, '信息确认'),
                    okText: getLabel(83446, '确定'),
                    cancelText: getLabel(31129, '取消'),
                    content: <div className="backComfirm" style={{ textAlign: 'center' }}>
                        <p style={{ fontSize: 13, marginBottom: 10 }}>{data.promptmsg}</p>
                        <p>
                            <WeaCheckbox ecId={`${this && this.props && this.props.ecId || ''}_WeaCheckbox@eypga7`} value={this.store1.getBackRunning()} onChange={(val) => {this.store1.setBackRunning(val)}} content={<span style={{ marginLeft: 10, color: 'red' }}>{getLabel(383601, '收回流转中的流程代理')}</span>} fieldName="wf-agent-backRunning" />
                        </p>
                    </div>,
                    onOk() {
                        message.loading(getLabel(383603, '正在收回，请稍候...'), 0);
                        // params["backRunning"] = jQuery("#wf-agent-backRunning").val();
                        params["backRunning"] = agentStore.getBackRunning();
                        jQuery('.backComfirm').remove();
                        WORKFLOW_AGENT.takeBackAgent(params).then((data) => {
                            if (data.flag) {
                                curStore.reload();
                                message.destroy();
                                message.success(getLabel(130233, '收回成功'));
                            } else {
                                message.destroy();
                                message.error(getLabel(383604, '收回失败'));
                            }
                        });
                        agentStore.setBackRunning(1);
                    },
                    onCancel() {
                        jQuery('.backComfirm').remove();
                        agentStore.setBackRunning(1);
                    }
                });
            });
        }

    }
};
window.agentOperate = operrate();

